package com.photography.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photography.common.JwtTokenUtils;
import com.photography.common.Result;

import com.photography.entity.Order;
import com.photography.entity.OrderItem;
import com.photography.entity.Product;
import com.photography.entity.ShippingAddress;
import com.photography.exception.ErrorCode;
import com.photography.mapper.OrderMapper;
import com.photography.service.OrderItemService;
import com.photography.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.photography.service.ProductService;
import com.photography.service.ShippingAddressService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


@Service
public class OrdersServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrdersService {
    @Resource
    private OrderItemService orderItemService;

    @Resource
    OrderMapper orderMapper;

    @Resource
    private ShippingAddressService shippingAddressService;

    private Integer getLoginUserId() {
        return Objects.requireNonNull(JwtTokenUtils.getCurrentUser()).getUserId();
    }

    /**
     * 创建订单
     */
    @Override
    @Transactional
    public Result createOrder(Order order) {
        // 参数校验
        if (order.getUserId() == null) {
            return Result.error("用户ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        if (order.getOrderAmount() == null || order.getOrderAmount().compareTo(java.math.BigDecimal.ZERO) <= 0) {
            return Result.error("订单金额必须大于0", ErrorCode.PARAM_ERROR.getCode());
        }

        // 设置默认值
        order.setOrderStatus("待支付");
        order.setOrderCreateTime(new Date());
        order.setUserId(getLoginUserId());

        // 保存订单
        this.save(order);
        Integer orderId = order.getOrderId();

        // 批量插入订单项
        List<OrderItem> items = order.getOrderItemList();
        items.forEach(item -> item.setOrderId(orderId));
        boolean result = orderItemService.saveBatch(items); // 批量插入方法
        if (result) {
            return Result.success(order, "创建订单成功");
        } else {
            return Result.error("创建订单失败");
        }
    }

    /**
     * 更新订单状态
     */
    @Override
    @Transactional
    public Result updateStatus(Integer orderId, String orderStatus) {
        if (orderId == null) {
            return Result.error("订单ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        if (!StringUtils.hasText(orderStatus)) {
            return Result.error("订单状态不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        Order order = this.getById(orderId);
        if (order == null) {
            return Result.error("订单不存在", ErrorCode.ORDER_NOT_EXIST.getCode());
        }
        if (!order.getUserId().equals(getLoginUserId())) {
            return Result.error("只允许更新自己的订单");
        }
        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setOrderStatus(orderStatus);
        boolean result = this.updateById(updateOrder);

        if (result) {
            return Result.success(null, "更新订单状态成功");
        } else {
            return Result.error("更新订单状态失败");
        }
    }

    /**
     * 更新所有
     */
    @Override
    public Result updateAll(Order order) {
        if (order.getOrderId() == null) {
            return Result.error("订单id不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        this.updateById(order); // 更新订单信息
        Integer orderId = order.getOrderId();

        ShippingAddress shippingAddress=order.getShippingAddress();
        if (shippingAddress!=null){
            boolean result = shippingAddressService.updateById(shippingAddress);
            if (result) {
                return Result.success(shippingAddress, "修改成功");
            } else {
                System.out.println(order);
                return Result.error("修改失败");
            }
        }

        // 处理订单项（修改而非插入）
        List<OrderItem> items = order.getOrderItemList();
        if (CollectionUtils.isNotEmpty(items)) {
            // 确保所有订单项关联到当前订单
            items.forEach(item -> item.setOrderId(orderId));
         //简单批量更新（需要每个订单项都有ID）
            boolean result = orderItemService.updateBatchById(items);
            if (result) {
                return Result.success(order, "更新订单成功");
            } else {
                return Result.error("更新订单失败");
            }
        } else {
            return Result.success(order, "更新订单成功（无订单项）");
        }
    }

    /**
     * 删除订单
     */
    @Override
    public Result deleteOrder(Integer orderId) {
        if (orderId == null) {
            return Result.error("订单ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        Order order = this.getById(orderId);
        if (order == null) {
            return Result.error("订单不存在", ErrorCode.ORDER_NOT_EXIST.getCode());
        }
        if (!order.getUserId().equals(getLoginUserId())) {
            return Result.error("只允许删除自己的订单");
        }
        boolean result = this.removeById(orderId);
        if (result) {
            return Result.success(null, "删除订单成功");
        } else {
            return Result.error("删除订单失败");
        }
    }

    /**
     * 分页查询订单
     */
    @Override
    public Page<Order> getOrdertPage(Page<Order> page, String orderStatus, Integer orderId) {
        // 获取当前用户角色
        String userRole = JwtTokenUtils.getCurrentRole();

        // 创建查询条件
        Order queryOrder = new Order();

        // 如果不是管理员，只能查看自己的订单
        if (!Objects.equals(userRole, "manager")) {
            queryOrder.setUserId(getLoginUserId());
        }
        if (orderStatus != null) {
            queryOrder.setOrderStatus(orderStatus);
        }
        if (Objects.equals(orderStatus, "全部订单")) {
            queryOrder.setOrderStatus(null);
        }
        if (orderId != null) {
            queryOrder.setOrderId(orderId);
        }
        // 查询订单列表
        List<Order> orders = orderMapper.findPage(queryOrder);

        // 计算分页
        int start = (int) ((page.getCurrent() - 1) * page.getSize());
        int end = Math.min(start + (int) page.getSize(), orders.size());

        // 设置分页结果
        page.setTotal(orders.size());
        page.setRecords(orders.subList(start, end));

        return page;
    }

    //    @Override
//    public Page<Map<String, Object>> getOrdertPage(Page<Order> page) {
//        String userRole=JwtTokenUtils.getCurrentRole();
//        if (!Objects.equals(userRole, "manager")){
//            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(Order::getUserId, getLoginUserId());
//            Page<Order> orderPage = page(page, queryWrapper);
//            List<Map<String, Object>> records = orderPage.getRecords().stream()
//                    .map(order -> {
//                        Map<String, Object> map = new HashMap<>();
//                        map.put("orderCreateTime", order.getOrderCreateTime());
//                        map.put("orderStatus", order.getOrderStatus());
//
//                        List<Map<String, Object>> itemList = new ArrayList<>();
//                        List<OrderItem> orderItems = orderItemService.list(new QueryWrapper<OrderItem>().eq("order_id", order.getOrderId()));
//
//                        for (OrderItem item : orderItems) {
//                            Product product = productService.getById(item.getProductId());
//                            Map<String, Object> itemMap = new HashMap<>();
//                            itemMap.put("id",item.getId());
//                            itemMap.put("orderId", item.getOrderId());
//                            itemMap.put("productId", item.getProductId());
//                            itemMap.put("quantity", item.getQuantity());
//                            itemMap.put("price", item.getPrice());
//                            itemMap.put("productName", product.getProductName());
//                            itemMap.put("englishName",product.getEnglishName());
//                            itemMap.put("scenarios",product.getScenarios());
//                            itemMap.put("imageUrls", product.getImageUrls()); // 添加图片URL
//                            itemList.add(itemMap);
//                        }
//
//                        map.put("orderItemList", itemList);
//                        return map;
//                    })
//                    .collect(Collectors.toList());
//
//// 创建新的Page对象，包含转换后的记录
//            Page<Map<String, Object>> resultPage = new Page<>(orderPage.getCurrent(), orderPage.getSize(), orderPage.getTotal());
//            resultPage.setRecords(records);
//
//            return resultPage;
//        }else {
//            return null;
//        }
//    }

    /**
     * 根据ID查询订单
     */
    @Override
    public Result findById(Integer orderId) {
        if (orderId == null) {
            return Result.error("订单ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            return Result.error("订单不存在", ErrorCode.ORDER_NOT_EXIST.getCode());
        }
        if (!order.getUserId().equals(getLoginUserId())) {
            return Result.error("只能查看自己的订单");
        }
        return Result.success(order);
    }


    //根据订单状态返回数据
    @Override
    public Result findOrderByStatus(Integer userId) {
        // 根据用户ID查询订单
        Order queryOrder = new Order();
        queryOrder.setUserId(userId);
        List<Order> orders = orderMapper.findPage(queryOrder);

        // 构建订单状态及其订单的树形结构
        List<Map<String, Object>> result = new ArrayList<>();

        // 定义订单状态列表
        List<String> statusList = Arrays.asList("待支付", "已支付", "待收货", "已完成");

        for (String status : statusList) {
            Map<String, Object> statusMap = new HashMap<>();
            statusMap.put("statusName", status);

            // 查找该状态下的所有订单
            List<Order> statusOrders = new ArrayList<>();
            for (Order order : orders) {
                if (status.equals(order.getOrderStatus())) {
                    statusOrders.add(order);
                }
            }

            // 将订单列表添加到状态的children属性中
            statusMap.put("children", statusOrders);
            result.add(statusMap);
        }

        return Result.success(result);
    }

    /**
     * 统计最近30天的每日订单量
     *
     * @return 返回日期和订单数量的统计结果
     */
    @Override
    public List<Map<String, Object>> getDailyOrderCount() {
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();

        // 获取30天前的日期
        calendar.add(Calendar.DAY_OF_MONTH, -30);
        Date thirtyDaysAgo = calendar.getTime();

        // 创建条件构造器
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(Order::getOrderCreateTime, thirtyDaysAgo)
                .le(Order::getOrderCreateTime, now);

        // 查询订单列表
        List<Order> orders = this.list(queryWrapper);

        // 使用Stream API按日期分组并计数
        Map<String, Long> dailyCount = orders.stream()
                .collect(Collectors.groupingBy(
                        order -> {
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(order.getOrderCreateTime());
                            return String.format("%d-%02d-%02d",
                                    cal.get(Calendar.YEAR),
                                    cal.get(Calendar.MONTH) + 1,
                                    cal.get(Calendar.DAY_OF_MONTH));
                        },
                        Collectors.counting()
                ));

        // 转换为所需的返回格式
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, Long> entry : dailyCount.entrySet()) {
            Map<String, Object> dailyData = new HashMap<>();
            dailyData.put("date", entry.getKey());
            dailyData.put("count", entry.getValue());
            result.add(dailyData);
        }

        // 按日期排序
        result.sort(Comparator.comparing(map -> (String) map.get("date")));

        return result;
    }

    //产品销量前三
    @Override
    public List<Map<String, Object>> getTopProductCount() {
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("product_name", "SUM(quantity) as count")
                .groupBy("product_name")
                .orderByDesc("count")
                .last("LIMIT 3");

        return orderItemService.getBaseMapper().selectMaps(queryWrapper);
    }

    /**
     * 获取最近30天产品分类销售分布
     *
     * @return 分类销售分布列表
     */
    @Override
    public List<Map<String, Object>> getCategoryDistribution() {
        return orderMapper.getCategoryDistribution();
    }

    /**
     * 获取今日统计数据
     *
     * @return 今日统计数据列表
     */
    @Override
    public List<Map<String, Object>> getTodayStatistics() {
        Map<String, Object> stats = orderMapper.getTodayStatistics();

        List<Map<String, Object>> result = new ArrayList<>();

        // 今日成交量
        Map<String, Object> orderCount = new HashMap<>();
        orderCount.put("id", 1);
        orderCount.put("title", "今日成交量");
        orderCount.put("data", stats.get("order_count"));
        result.add(orderCount);

        // 今日成交额
        Map<String, Object> orderAmount = new HashMap<>();
        orderAmount.put("id", 2);
        orderAmount.put("title", "今日成交额");
        orderAmount.put("data", stats.get("order_amount"));
        result.add(orderAmount);

        // 今日用户数
        Map<String, Object> userCount = new HashMap<>();
        userCount.put("id", 3);
        userCount.put("title", "今日新增用户数");
        userCount.put("data", stats.get("user_count"));
        result.add(userCount);

        // 用户总数
        Map<String, Object> userAllCount = new HashMap<>();
        userAllCount.put("id", 3);
        userAllCount.put("title", "用户总数");
        userAllCount.put("data", stats.get("user_allcount"));
        result.add(userAllCount);

        return result;
    }
}
